﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System.Text;
using System;
using System.Threading.Tasks;
using ZY.VICS.RabbitMQ.PubsubMode;

namespace JT1078.Gateway
{
    public interface ITerminalCommandPublisher
    {
        void Publish(BaseEventArgs eventData);
        Task PublishAsync(BaseEventArgs eventData);
    }

    public class TerminalCommandPublisher : ITerminalCommandPublisher
    {
        protected IPubFactory _pub;
        protected IPub _producer;
        protected ILogger<TerminalCommandPublisher> _logger;
        public TerminalCommandPublisher(IPubFactory pub, ILogger<TerminalCommandPublisher> logger)
        {
            _pub = pub;
            _logger = logger;
        }

        public void Publish(BaseEventArgs eventData)
        {
            PublishMsg(eventData);
        }

        public async Task PublishAsync(BaseEventArgs eventData)
        {
            PublishMsg(eventData);
            await Task.CompletedTask;
        }

        private void PublishMsg(BaseEventArgs eventData)
        {
            try
            {
                var jo = new JObject();
                //jo.Add("mVehicleIP", mVehicleIP);
                jo.Add("mCommandDescrib", "");
                //jo.Add("mCommandSerial", m_CommandSerial);
                //jo.Add("mCommmandType", m_CommmandType);
                jo.Add("mDevicenumber", eventData.Id);
                //jo.Add("mSendUserClientId", m_SendUserClientId);
                //jo.Add("mUserId", m_UserId);
                jo.Add("mTerminalType", (ushort)48); //48
                                                     //jo.Add("mVehicleID", mVehicleID);
                jo.Add("mBytes", eventData.Bytes.ToArray());

                var body = Encoding.UTF8.GetBytes(jo.ToString());

                _producer = _pub.Create(new ExchangeDeclareConfiguration("UserCmd", ExchangeType.Fanout));
                _producer.Publish(body, eventData.Id);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布终端指令时发生错误");
            }
        }
    }
}